package com.example.lib_http.download

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.File

object DownloadManager {
    fun download(url:String,file: File):Flow<DownState>{
        return flow {
            val request =
                Request.Builder().url(url).addHeader("Accept-Encoding", "identity").get().build()
            val response = OkHttpClient.Builder().build().newCall(request).execute()
            if(response.isSuccessful){
                response.body().let {b->
                    file.outputStream().let {
                        b?.byteStream()?.apply {
                            var len=0
                            var bufferSize= DEFAULT_BUFFER_SIZE
                            val array = ByteArray(bufferSize)
                            var read = read(array)
                                while (read>=0){
                                    it.write(array,0,len)
                                    len+=read
                                    read=read(array)
                                }
                            emit(DownState.Done(file))
                        }

                    }

                }
            }
        }.flowOn(Dispatchers.IO)
    }
}